package com.life.ai.server.modules.develop.service.impl;

import cn.hutool.http.useragent.UserAgent;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.life.ai.server.common.domain.PageQuery;
import com.life.ai.server.common.utils.AddressUtils;
import com.life.ai.server.common.utils.ServletUtils;
import com.life.ai.server.framework.config.properties.SystemProperties;
import com.life.ai.server.modules.develop.entity.SysLoginLog;
import com.life.ai.server.modules.develop.mapper.SysLoginLogMapper;
import com.life.ai.server.modules.develop.service.SysLoginLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 系统登录日志 服务实现类
 * </p>
 *
 * @author kyle
 * @since 2024-06-14
 */
@Service
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements SysLoginLogService {

    /**
     * 分页查询
     *
     * @param pageQuery 分页参数
     * @param sysLoginLog 查询条件
     * @return Page<SysLoginLog>
     */
    @Override
    public Page<SysLoginLog> queryPage(PageQuery pageQuery,SysLoginLog sysLoginLog){
        return lambdaQuery().page(pageQuery.build());
    }

    /**
     * 保存登录记录
     *
     * @param username 用户名
     * @param status   状态
     * @param message  消息内容
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveLoginRecord(String username, String status, String message) {
        UserAgent userAgent = ServletUtils.getUserAgent();
        String ip = ServletUtils.getClientIP();
        String address = SystemProperties.saveLoginLocation ? AddressUtils.getRealAddressByIP(ip) : "未知";
        // 构建登录信息
        SysLoginLog loginLog = new SysLoginLog()
                .setUsername(username)
                .setStatus(status)
                .setMsg(message)
                .setIpaddr(ip)
                .setLoginLocation(address)
                .setOs(userAgent.getOs().getName())
                .setBrowser(userAgent.getBrowser().getName())
                .setLoginTime(new Date());
        this.save(loginLog);
    }
}

